#include "socket_deal_with.h"

int socket_start(int *socket_fd, char *ip_addr){
	int ret = 1;
	struct sockaddr_in server_addr;
	*socket_fd = socket(AF_INET, SOCK_STREAM, 0);
	if(*socket_fd == -1){
		perror("create socket fail!\n");
		ret = 0;
	}
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = inet_addr(ip_addr);
	server_addr.sin_port = htons(MYPORT);
	bzero(&(server_addr.sin_zero), 8);

	if(connect(*socket_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1){
		printf("connect socket fail! \n");
		close(*socket_fd);
		ret = 0;
	}
	return ret;
}

int pthread_socket_start(){
	pthread_t tid;
	int ret = pthread_create(&tid, NULL, (void *)&socket_start, NULL);
	if(ret != 0){
		printf("create pthread fail!\n");
	}
	return ret;
}

int socket_send_request(char *userinfo){
	int socket_fd;
	if(!socket_start(&socket_fd, "127.0.0.1"))
		return 0;

	if((send(socket_fd, userinfo, MAXUSERINFOSIZE, 0)) < 0){
		perror("send error\n");
		return 0;
	}
	char buf[128];
	int bytes;
	if((bytes = recv(socket_fd, buf, 128, 0 )) == -1){
		printf("receive err\n");
		return 0;
	}
	buf[bytes] = '\0';
	printf("buf :%s, bytes :%d\n", buf, bytes);
	if(strcmp(buf, "err") == 0){
		return 0;
	}

	close(socket_fd);
	return 1;
}

int socket_send_request_needRet(char *userinfo, char *recvRet){
	int socket_fd;
	if(!socket_start(&socket_fd, "127.0.0.1"))
		return 0;

	if((send(socket_fd, userinfo, MAXUSERINFOSIZE, 0)) < 0){
		perror("send error\n");
		return 0;
	}
	char buf[128];
	int bytes;
	if((bytes = recv(socket_fd, buf, 128, 0 )) == -1){
		printf("receive err\n");
		return 0;
	}
	buf[bytes] = '\0';
	printf("buf :%s, bytes :%d\n", buf, bytes);
	strncpy(recvRet, buf, strlen(buf));
	close(socket_fd);
	return 1;
}
char *socket_getUserFriends(char *userinfo){
	userinfo[0] = '3';
	printf("%s\n", userinfo);
	static char recvRet[20];
	memset(recvRet, 0, 20);
	if(socket_send_request_needRet(userinfo, recvRet)){
		printf("socket_send_request_needRet, recvRet:%s\n",recvRet);
		int len = strlen(recvRet);
		recvRet[len - 1] ='\0';
	}
	return recvRet;
}

char *socket_getUserName(char *userinfo){
	userinfo[0] = '3';
	printf("%s\n", userinfo);
	static char recvRet[20];
	memset(recvRet, 0, 20);
	if(socket_send_request_needRet(userinfo, recvRet)){
		int len = strlen(recvRet);
		recvRet[len - 1] ='\0';
	}
	return recvRet;
}

char *socket_setUserFlag(char *userinfo){
	userinfo[0] = '4';
	printf("%s\n", userinfo);
	socket_send_request(userinfo);
}

